//
//  ViewController.m
//  YiXiaoBao
//
//  Created by 暗流澎涌 on 2025/7/18.
//

#import "ViewController.h"
#import "MemoryBoardViewController.h"
#import "ItemRecordViewController.h"
#import "PersonalCenterViewController.h"

@interface ViewController ()
@property (nonatomic, strong) UILabel *reminderContent; // 今日提醒内容标签
@property (nonatomic, strong) NSArray *memoryItems; // 提醒事项数据
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 设置渐变背景 - 与MemoryBoardViewController保持一致
    CAGradientLayer *backgroundGradient = [CAGradientLayer layer];
    backgroundGradient.colors = @[(__bridge id)[UIColor colorWithRed:0.96 green:0.98 blue:1.0 alpha:1.0].CGColor,
                                  (__bridge id)[UIColor colorWithRed:0.94 green:0.96 blue:1.0 alpha:1.0].CGColor];
    backgroundGradient.frame = self.view.bounds;
    [self.view.layer insertSublayer:backgroundGradient atIndex:0];
    
    // 设置导航栏
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:0.26 green:0.54 blue:0.96 alpha:1.0];
    self.navigationController.navigationBar.titleTextAttributes = @{
        NSForegroundColorAttributeName: [UIColor blackColor],
        NSFontAttributeName: [UIFont systemFontOfSize:20 weight:UIFontWeightMedium]
    };
    self.title = @"老人记忆";
    self.navigationController.navigationBar.tintColor = [UIColor blackColor];
    
    CGFloat width = self.view.bounds.size.width;
    CGFloat safeAreaTop = self.view.safeAreaInsets.top;
    
    // 重新设计顶部卡片区域
    UIView *headerCard = [[UIView alloc] initWithFrame:CGRectMake(20, safeAreaTop + 100, width - 40, 200)];
    headerCard.backgroundColor = [UIColor whiteColor];
    headerCard.layer.cornerRadius = 24;
    headerCard.layer.shadowColor = [UIColor colorWithRed:0.26 green:0.54 blue:0.96 alpha:0.15].CGColor;
    headerCard.layer.shadowOpacity = 1;
    headerCard.layer.shadowOffset = CGSizeMake(0, 8);
    headerCard.layer.shadowRadius = 20;
    [self.view addSubview:headerCard];
    
    // 添加装饰性图标
    UIImageView *iconView = [[UIImageView alloc] initWithFrame:CGRectMake(headerCard.bounds.size.width - 80, 20, 60, 60)];
//    iconView.image = [UIImage systemImageNamed:@"brain.head.profile"];
    iconView.tintColor = [UIColor colorWithRed:0.26 green:0.54 blue:0.96 alpha:0.3];
    iconView.contentMode = UIViewContentModeScaleAspectFit;
    [headerCard addSubview:iconView];
    
    // 问候语优化
    UILabel *helloLabel = [[UILabel alloc] initWithFrame:CGRectMake(24, 30, headerCard.bounds.size.width - 120, 36)];
    helloLabel.text = @"您好";
    helloLabel.font = [UIFont systemFontOfSize:28 weight:UIFontWeightBold];
    helloLabel.textColor = [UIColor colorWithRed:0.2 green:0.2 blue:0.2 alpha:1.0];
    [headerCard addSubview:helloLabel];
    
    // 日期标签优化
    UILabel *dateLabel = [[UILabel alloc] initWithFrame:CGRectMake(24, 70, headerCard.bounds.size.width - 48, 24)];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy年M月d日 "];
    dateLabel.text = [formatter stringFromDate:[NSDate date]];
    dateLabel.font = [UIFont systemFontOfSize:16 weight:UIFontWeightMedium];
    dateLabel.textColor = [UIColor colorWithRed:0.5 green:0.5 blue:0.5 alpha:1.0];
    [headerCard addSubview:dateLabel];
    
    // 今日提醒区域重新设计
    UIView *reminderSection = [[UIView alloc] initWithFrame:CGRectMake(24, 110, headerCard.bounds.size.width - 48, 70)];
    reminderSection.backgroundColor = [UIColor colorWithRed:0.96 green:0.98 blue:1.0 alpha:1.0];
    reminderSection.layer.cornerRadius = 16;
    reminderSection.layer.borderWidth = 1;
    reminderSection.layer.borderColor = [UIColor colorWithRed:0.26 green:0.54 blue:0.96 alpha:0.2].CGColor;
    [headerCard addSubview:reminderSection];
    
    UILabel *reminderIcon = [[UILabel alloc] initWithFrame:CGRectMake(16, 12, 24, 24)];
    reminderIcon.text = @"🔔";
    reminderIcon.font = [UIFont systemFontOfSize:20];
    [reminderSection addSubview:reminderIcon];
    
    UILabel *reminderTitle = [[UILabel alloc] initWithFrame:CGRectMake(48, 12, reminderSection.bounds.size.width - 64, 22)];
    reminderTitle.text = @"今日重要提醒";
    reminderTitle.font = [UIFont systemFontOfSize:16 weight:UIFontWeightSemibold];
    reminderTitle.textColor = [UIColor colorWithRed:0.26 green:0.54 blue:0.96 alpha:1.0];
    [reminderSection addSubview:reminderTitle];
    
    self.reminderContent = [[UILabel alloc] initWithFrame:CGRectMake(48, 36, reminderSection.bounds.size.width - 64, 20)];
    self.reminderContent.text = @"记得吃降压药  上午9:00 - 还有30分钟";
    self.reminderContent.font = [UIFont systemFontOfSize:14];
    self.reminderContent.textColor = [UIColor colorWithRed:0.4 green:0.4 blue:0.4 alpha:1.0];
    [reminderSection addSubview:self.reminderContent];
    
    // 功能按钮区域重新设计
    CGFloat buttonY = CGRectGetMaxY(headerCard.frame) + 30;
    CGFloat buttonWidth = (width - 60) / 2;
    CGFloat buttonHeight = 140;
    
    // 黄金记忆板按钮
    UIView *memoryButtonContainer = [[UIView alloc] initWithFrame:CGRectMake(20, buttonY, buttonWidth, buttonHeight)];
    [self.view addSubview:memoryButtonContainer];
    
    UIButton *memoryBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    memoryBtn.frame = memoryButtonContainer.bounds;
    memoryBtn.backgroundColor = [UIColor whiteColor];
    memoryBtn.layer.cornerRadius = 20;
    memoryBtn.layer.shadowColor = [UIColor colorWithRed:0.26 green:0.54 blue:0.96 alpha:0.15].CGColor;
    memoryBtn.layer.shadowOpacity = 1;
    memoryBtn.layer.shadowOffset = CGSizeMake(0, 6);
    memoryBtn.layer.shadowRadius = 15;
    [memoryBtn addTarget:self action:@selector(gotoMemoryBoard) forControlEvents:UIControlEventTouchUpInside];
    [memoryButtonContainer addSubview:memoryBtn];
    
    // 添加图标
    UIImageView *memoryIcon = [[UIImageView alloc] initWithFrame:CGRectMake((buttonWidth - 50) / 2, 25, 50, 50)];
    memoryIcon.image = [UIImage systemImageNamed:@"brain"];
    memoryIcon.tintColor = [UIColor colorWithRed:0.26 green:0.54 blue:0.96 alpha:1.0];
    memoryIcon.contentMode = UIViewContentModeScaleAspectFit;
    [memoryBtn addSubview:memoryIcon];
    
    UILabel *memoryTitle = [[UILabel alloc] initWithFrame:CGRectMake(10, 85, buttonWidth - 20, 24)];
    memoryTitle.text = @"黄金记忆板";
    memoryTitle.font = [UIFont systemFontOfSize:18 weight:UIFontWeightBold];
    memoryTitle.textAlignment = NSTextAlignmentCenter;
    memoryTitle.textColor = [UIColor colorWithRed:0.2 green:0.2 blue:0.2 alpha:1.0];
    [memoryBtn addSubview:memoryTitle];
    
    UILabel *memorySubtitle = [[UILabel alloc] initWithFrame:CGRectMake(10, 110, buttonWidth - 20, 20)];
    memorySubtitle.text = @"重要事项提醒";
    memorySubtitle.font = [UIFont systemFontOfSize:14];
    memorySubtitle.textAlignment = NSTextAlignmentCenter;
    memorySubtitle.textColor = [UIColor colorWithRed:0.5 green:0.5 blue:0.5 alpha:1.0];
    [memoryBtn addSubview:memorySubtitle];
    
    // 记住这东西按钮
    UIView *itemButtonContainer = [[UIView alloc] initWithFrame:CGRectMake(40 + buttonWidth, buttonY, buttonWidth, buttonHeight)];
    [self.view addSubview:itemButtonContainer];
    
    UIButton *itemBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    itemBtn.frame = itemButtonContainer.bounds;
    itemBtn.backgroundColor = [UIColor whiteColor];
    itemBtn.layer.cornerRadius = 20;
    itemBtn.layer.shadowColor = [UIColor colorWithRed:0.26 green:0.54 blue:0.96 alpha:0.15].CGColor;
    itemBtn.layer.shadowOpacity = 1;
    itemBtn.layer.shadowOffset = CGSizeMake(0, 6);
    itemBtn.layer.shadowRadius = 15;
    [itemBtn addTarget:self action:@selector(gotoItemRecord) forControlEvents:UIControlEventTouchUpInside];
    [itemButtonContainer addSubview:itemBtn];
    
    // 添加图标
    UIImageView *itemIcon = [[UIImageView alloc] initWithFrame:CGRectMake((buttonWidth - 50) / 2, 25, 50, 50)];
    itemIcon.image = [UIImage systemImageNamed:@"location.magnifyingglass"];
    itemIcon.tintColor = [UIColor colorWithRed:0.96 green:0.54 blue:0.26 alpha:1.0];
    itemIcon.contentMode = UIViewContentModeScaleAspectFit;
    [itemBtn addSubview:itemIcon];
    
    UILabel *itemTitle = [[UILabel alloc] initWithFrame:CGRectMake(10, 85, buttonWidth - 20, 24)];
    itemTitle.text = @"记住这东西";
    itemTitle.font = [UIFont systemFontOfSize:18 weight:UIFontWeightBold];
    itemTitle.textAlignment = NSTextAlignmentCenter;
    itemTitle.textColor = [UIColor colorWithRed:0.2 green:0.2 blue:0.2 alpha:1.0];
    [itemBtn addSubview:itemTitle];
    
    UILabel *itemSubtitle = [[UILabel alloc] initWithFrame:CGRectMake(10, 110, buttonWidth - 20, 20)];
    itemSubtitle.text = @"物品位置记录";
    itemSubtitle.font = [UIFont systemFontOfSize:14];
    itemSubtitle.textAlignment = NSTextAlignmentCenter;
    itemSubtitle.textColor = [UIColor colorWithRed:0.5 green:0.5 blue:0.5 alpha:1.0];
    [itemBtn addSubview:itemSubtitle];
    
    // 底部快捷操作区域
    CGFloat quickActionY = buttonY + buttonHeight + 30;
//    UIView *quickActionCard = [[UIView alloc] initWithFrame:CGRectMake(20, quickActionY, width - 40, 80)];
//    quickActionCard.backgroundColor = [UIColor whiteColor];
//    quickActionCard.layer.cornerRadius = 20;
//    quickActionCard.layer.shadowColor = [UIColor colorWithRed:0.26 green:0.54 blue:0.96 alpha:0.1].CGColor;
//    quickActionCard.layer.shadowOpacity = 1;
//    quickActionCard.layer.shadowOffset = CGSizeMake(0, 4);
//    quickActionCard.layer.shadowRadius = 10;
//    [self.view addSubview:quickActionCard];
//    
//    UILabel *quickTitle = [[UILabel alloc] initWithFrame:CGRectMake(20, 15, quickActionCard.bounds.size.width - 40, 20)];
//    quickTitle.text = @"快捷操作";
//    quickTitle.font = [UIFont systemFontOfSize:16 weight:UIFontWeightSemibold];
//    quickTitle.textColor = [UIColor colorWithRed:0.3 green:0.3 blue:0.3 alpha:1.0];
//    [quickActionCard addSubview:quickTitle];
//    
//    // 快捷按钮
//    NSArray *quickActions = @[@"📝 快速记录", @"🔍 查找物品", @"⏰ 设置提醒"];
//    CGFloat quickBtnWidth = (quickActionCard.bounds.size.width - 80) / 3;
//    for (int i = 0; i < quickActions.count; i++) {
//        UIButton *quickBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//        quickBtn.frame = CGRectMake(20 + i * (quickBtnWidth + 10), 45, quickBtnWidth, 25);
//        quickBtn.backgroundColor = [UIColor colorWithRed:0.96 green:0.98 blue:1.0 alpha:1.0];
//        quickBtn.layer.cornerRadius = 12;
//        [quickBtn setTitle:quickActions[i] forState:UIControlStateNormal];
//        [quickBtn setTitleColor:[UIColor colorWithRed:0.26 green:0.54 blue:0.96 alpha:1.0] forState:UIControlStateNormal];
//        quickBtn.titleLabel.font = [UIFont systemFontOfSize:12];
//        [quickActionCard addSubview:quickBtn];
//    }
//    
    // 右上角设置按钮
    UIBarButtonItem *settingBtn = [[UIBarButtonItem alloc] initWithImage:[UIImage systemImageNamed:@"gearshape.fill"] style:UIBarButtonItemStylePlain target:self action:@selector(gotoSetting)];
    self.navigationItem.rightBarButtonItem = settingBtn;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    // 每次页面即将显示时刷新今日提醒数据
    [self loadAndUpdateTodayReminders];
}

// 加载并更新今日提醒数据
- (void)loadAndUpdateTodayReminders {
    // 从NSUserDefaults加载提醒事项数据
    NSArray *savedItems = [[NSUserDefaults standardUserDefaults] objectForKey:@"memoryItems"];
    self.memoryItems = savedItems ?: @[];
    
    // 获取今日的提醒事项
    NSArray *todayItems = [self getTodayReminders];
    
    // 更新今日提醒显示
    [self updateTodayReminderDisplay:todayItems];
}

// 获取今日的提醒事项，只显示未过时的数据
- (NSArray *)getTodayReminders {
    NSMutableArray *upcomingItems = [NSMutableArray array]; // 未过时的事项
    
    // 获取当前时间
    NSDate *now = [NSDate date];
    NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];
    timeFormatter.dateFormat = @"HH:mm";
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    // 筛选今日未完成且未过时的提醒事项
    for (NSDictionary *item in self.memoryItems) {
        // 只显示未完成的事项
        if (![item[@"done"] boolValue]) {
            NSString *timeString = item[@"time"];
            NSDate *reminderTime = [timeFormatter dateFromString:timeString];
            
            if (reminderTime) {
                // 获取今天的日期
                NSDateComponents *todayComponents = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:now];
                NSDateComponents *reminderComponents = [calendar components:NSCalendarUnitHour | NSCalendarUnitMinute fromDate:reminderTime];
                
                // 组合成今天的提醒时间
                todayComponents.hour = reminderComponents.hour;
                todayComponents.minute = reminderComponents.minute;
                todayComponents.second = 0;
                
                NSDate *todayReminderTime = [calendar dateFromComponents:todayComponents];
                
                // 只添加未过时的事项
                if ([todayReminderTime timeIntervalSinceDate:now] >= 0) {
                    [upcomingItems addObject:item]; // 未过时
                }
            } else {
                // 如果时间格式有问题，放到未过时列表中
                [upcomingItems addObject:item];
            }
        }
    }
    
    // 按时间排序
    [upcomingItems sortUsingComparator:^NSComparisonResult(NSDictionary *item1, NSDictionary *item2) {
        NSString *time1 = item1[@"time"];
        NSString *time2 = item2[@"time"];
        return [time1 compare:time2];
    }];
    
    return upcomingItems;
}

// 更新今日提醒显示
- (void)updateTodayReminderDisplay:(NSArray *)todayItems {
    if (todayItems.count == 0) {
        // 没有未过时的提醒事项时显示占位文字
        self.reminderContent.text = @"今日暂无重要提醒";
        self.reminderContent.textColor = [UIColor colorWithRed:0.6 green:0.6 blue:0.6 alpha:1.0];
    } else {
        // 显示最近的一个未过时提醒事项
        NSDictionary *nextItem = todayItems.firstObject;
        NSString *title = nextItem[@"title"];
        NSString *time = nextItem[@"time"];
        
        // 计算距离提醒时间还有多久
        NSString *timeInfo = [self getTimeInfoForReminder:time];
        
        self.reminderContent.text = [NSString stringWithFormat:@"%@  %@ - %@", title, time, timeInfo];
        self.reminderContent.textColor = [UIColor colorWithRed:0.4 green:0.4 blue:0.4 alpha:1.0];
    }
}

// 计算距离提醒时间的信息
- (NSString *)getTimeInfoForReminder:(NSString *)timeString {
    NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];
    timeFormatter.dateFormat = @"HH:mm";
    
    NSDate *reminderTime = [timeFormatter dateFromString:timeString];
    if (!reminderTime) {
        return @"";
    }
    
    // 获取今天的日期
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDate *now = [NSDate date];
    NSDateComponents *todayComponents = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:now];
    NSDateComponents *reminderComponents = [calendar components:NSCalendarUnitHour | NSCalendarUnitMinute fromDate:reminderTime];
    
    // 组合成今天的提醒时间
    todayComponents.hour = reminderComponents.hour;
    todayComponents.minute = reminderComponents.minute;
    todayComponents.second = 0;
    
    NSDate *todayReminderTime = [calendar dateFromComponents:todayComponents];
    
    // 计算时间差
    NSTimeInterval timeDifference = [todayReminderTime timeIntervalSinceDate:now];
    
    if (timeDifference < 0) {
        return @"已过时";
    } else if (timeDifference < 3600) { // 小于1小时
        NSInteger minutes = (NSInteger)(timeDifference / 60);
        return [NSString stringWithFormat:@"还有%ld分钟", (long)minutes];
    } else { // 大于1小时
        NSInteger hours = (NSInteger)(timeDifference / 3600);
        NSInteger minutes = (NSInteger)((timeDifference - hours * 3600) / 60);
        if (minutes > 0) {
            return [NSString stringWithFormat:@"还有%ld小时%ld分钟", (long)hours, (long)minutes];
        } else {
            return [NSString stringWithFormat:@"还有%ld小时", (long)hours];
        }
    }
}

// 跳转黄金记忆板
- (void)gotoMemoryBoard {
    MemoryBoardViewController *vc = [[MemoryBoardViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

// 跳转记住这东西
- (void)gotoItemRecord {
    ItemRecordViewController *vc = [[ItemRecordViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

// 跳转设置 - 修改为跳转到个人中心
- (void)gotoSetting {
    PersonalCenterViewController *personalCenterVC = [[PersonalCenterViewController alloc] init];
    [self.navigationController pushViewController:personalCenterVC animated:YES];
}

@end

